import { _decorator, Component, Prefab, Node, Label, Graphics, Event, director, v3, v2, instantiate, RigidBody2D, CircleCollider2D, PhysicsSystem2D, error, EventTouch, UITransform, AudioClip, tween, randomRangeInt, Color, log, ERigidBody2DType, UIOpacity, Vec2, Vec3, easing, ERaycast2DType, EPhysics2DDrawFlags, Director, PHYSICS_2D_PTM_RATIO } from 'cc';
import { SSS_Consts } from "../../../Script/Data/SSS_Consts";
import { bdlMgr } from "../../../Script/Manager/BundleManager_S";
import UI from "../../../Script/Manager/UI";
import HeChengDaXiGua_Fruit from "./HeChengDaXiGua_Fruit";
import { HeChengDaXiGua_GameData } from "./HeChengDaXiGua_GameData";
import HeChengDaXiGua_GamePanel from "./HeChengDaXiGua_GamePanel";
import { HeChengDaXiGua_GameStorage } from "./HeChengDaXiGua_GameStorage";
import HeChengDaXiGua_LosePanel from "./HeChengDaXiGua_LosePanel";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

const { ccclass, property } = _decorator;

@ccclass('HeChengDaXiGuaGameManager')
export default class HeChengDaXiGua_GameManager extends Component {
        public static Instance: HeChengDaXiGua_GameManager;

        @property([Prefab])
        fruitPrefabs: Prefab[] = [];
        @property(Node)
        touchLayer: Node | null = null;
        @property(Node)
        fruitLayer: Node | null = null;
        @property(Node)
        lineLayer: Node | null = null;
        @property(Node)
        DeadLine: Node | null = null;
        @property(Node)
        groundNode: Node | null = null; // 新增地面节点属性
        @property(Node)
        next: Node | null = null;
        @property(Label)
        scoreLabel: Label | null = null;

        @property(Node)
        移动父物体: Node = null;
        @property(Node)
        云: Node = null;
        @property(Node)
        预览水果: Node = null;
        @property(Node)
        当前水果: Node = null;

        @property(Node)
        Root_main: Node | null = null;
        @property(Node)
        地: Node = null;

        // @property({ tooltip: '是否开启物理调试可视化' })
        // debugPhysics: boolean = false;

        previewFruit: Node = null;

        private currentFruit: Node | null = null;
        private nextFruitLevel: number = 1; // 下一个水果的等级
        //    // private nextFruitPreview: Node = null; // 下一个水果的预览节点
        //    // private score: number = 0;
        private isGameOver: boolean = false;
        private isDragging: boolean = false;
        private lastSaveTipTime: number = 0; // 上次显示保存提示的时间
        //    // 竖线节点和组件
        private guideLineNode: Node | null = null;
        private guideLineGraphics: Graphics | null = null;
        //    // 虚线动画偏移
        private dashOffset: number = 0;
        //    // start_y: number = 300;
        //    // 检查延迟帧数（几帧内持续超过高度才失败）
        //    // @property
        //    // checkDelayFrames: number = 30;
        //    // private dangerHeight = 500;
        private speedThreshold = 1; // 速度阈值
        private dangerFrameThreshold = 24 * 3; // 连续x帧满足条件才判输
        private dangerFrameCount = 0;
        //    // private overFrameCount: number = 0;
        x1 = 0// 150;
        y1 = 100//100;

        onLoad() {
                HeChengDaXiGua_GameManager.Instance = this;

                // PhysicsSystem2D.instance.gravity = v2(0, -980);
                // PhysicsSystem2D.instance.gravity = v2(0, -980 * 4);
                const g_m = 98;
                PhysicsSystem2D.instance.gravity = new Vec2(0, - g_m * PHYSICS_2D_PTM_RATIO);
                // PhysicsSystem2D.instance.physicsWorld.setPixelsPerMeter(100); // 1米=100像素

                // 优化物理系统配置
                // PhysicsSystem2D.instance.velocityIterations = 8;
                // PhysicsSystem2D.instance.positionIterations = 8;

                // PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Aabb |
                //         EPhysics2DDrawFlags.Pair |
                //         EPhysics2DDrawFlags.CenterOfMass |
                //         EPhysics2DDrawFlags.Joint |
                //         EPhysics2DDrawFlags.Shape;

                // 提高物理步进精度，减少穿透 // 设置物理步长
                PhysicsSystem2D.instance.fixedTimeStep = 1 / 120;
                // director.getCollisionManager().enabled = true;
                // PhysicsSystem2D.instance.enable = true;
                PhysicsSystem2D.instance.enable = true;


                // 初始化下一个水果等级
                this.initNextFruitLevel();

                // 然后初始化游戏数据
                this.Init();

                if (this.touchLayer) {
                        this.touchLayer.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
                        this.touchLayer.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
                        this.touchLayer.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
                } else {
                        error("请绑定 touchLayer 节点");
                }

                this.scheduleOnce(() => {
                        this.spawnNextFruit();
                }, 0.2);

                // 定期自动保存（每2秒保存一次）
                // this.schedule(this.autoSave, 2);
                this.schedule(this.autoSave, 2);

                // 监听应用暂停事件
                // game.on(game.EVENT_HIDE, this.onAppHide, this);
        }

        start() {
                // 立即更新预览，确保游戏开始时就显示
                this.scheduleOnce(() => {
                        this.updateNextFruitPreview();
                }, 0.01)
        }
        //    
        async Init() {
                HeChengDaXiGua_GameStorage.initData();
                HeChengDaXiGua_GameData.ClearData();
                HeChengDaXiGua_GameData.InitData();

                HeChengDaXiGua_GamePanel.Instance.ShowOn();

                await new Promise<void>((resolve) => {
                        director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                });
                this.loadSavedGameState();

                // // 延迟一帧后加载保存的游戏状态，确保物理系统完全初始化
                // this.scheduleOnce(() => {
                //         this.loadSavedGameState();
                // }, 0);
        }
        //    // 加载保存的游戏状态
        loadSavedGameState() {
                const savedData = HeChengDaXiGua_GameStorage.loadFruitsData();

                // console.log(`savedData-------`, savedData);

                if (savedData.fruits.length > 0) {
                        // 恢复分数
                        HeChengDaXiGua_GameData.Score = savedData.currentScore;
                        HeChengDaXiGua_GamePanel.Instance.Refresh_score();

                        // 恢复所有水果
                        savedData.fruits.forEach(fruitData => {
                                this.restoreFruit(fruitData);
                        });

                        console.log(`恢复了 ${savedData.fruits.length} 个水果的状态`);
                }
        }

        //    // 恢复单个水果
        async restoreFruit(fruitData: any) {
                await new Promise<void>((resolve) => {
                        director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                });

                // 检查物理系统是否已初始化
                const physicsManager = PhysicsSystem2D// director.getPhysicsManager();
                // if (!physicsManager || !physicsManager.enabled) {
                if (!physicsManager || !physicsManager.instance || !physicsManager.instance.enable) {
                        console.warn("物理系统未初始化，延迟恢复水果");
                        this.scheduleOnce(() => this.restoreFruit(fruitData), 0.1);
                        return;
                }

                if (fruitData.level > this.fruitPrefabs.length) {
                        console.warn(`水果等级 ${fruitData.level} 超出预制体范围`);
                        return;
                }

                const prefab = this.fruitPrefabs[fruitData.level - 1];
                if (!prefab) {
                        console.error(`没有找到等级 ${fruitData.level} 的水果预制体`);
                        return;
                }

                const fruit = instantiate(prefab);
                fruit.parent = this.fruitLayer;
                fruit.setPosition(fruitData.x, fruitData.y);
                fruit.angle = fruitData.rotation;
                // fruit.eulerAngles = v3(fruit.eulerAngles.x, fruit.eulerAngles.y, fruitData.rotation);
                // rotation: fruitNode.eulerAngles.z,


                const rigid = fruit.getComponent(RigidBody2D);
                if (rigid) {
                        rigid.bullet = true; // 开启高速防穿透
                        // rigid.type = RigidBodyType.Dynamic;
                        rigid.type = ERigidBody2DType.Dynamic;
                        rigid.gravityScale = 1;
                        rigid.linearDamping = 0.8;
                        rigid.angularDamping = 0.8;
                        // rigid.awake = true;
                        rigid.wakeUp();
                        rigid.linearVelocity = v2(fruitData.linearVelocityX, fruitData.linearVelocityY);
                        rigid.angularVelocity = fruitData.angularVelocity;
                        // 确保刚体被物理系统识别
                        // rigid.enabled = true;
                }

                // 启用碰撞体并设置正确的属性
                // const collider = fruit.getComponent(PhysicsCircleCollider);
                const collider = fruit.getComponent(CircleCollider2D);
                if (collider) {
                        collider.enabled = true;
                        // 确保碰撞体被物理系统识别
                        collider.sensor = false;
                        // 设置碰撞体的摩擦力和弹性
                        collider.friction = 0.1;
                        collider.restitution = 0.3;
                        // 根据等级设置密度
                        collider.density = this.getDensityByLevel(fruitData.level);
                }

                const fruitScript = fruit.getComponent(HeChengDaXiGua_Fruit);
                if (fruitScript) {
                        fruitScript.setGameManager(this);
                        fruitScript.level = fruitData.level;
                        fruitScript.isMerged = false;
                        fruitScript.isLanded = false;
                        // 确保水果脚本的碰撞体引用正确
                        fruitScript.collider = collider;

                        // 手动调用水果脚本的初始化逻辑，确保密度等属性正确设置
                        if (fruitScript.collider) {
                                fruitScript.collider.friction = 0.1;
                                fruitScript.collider.restitution = 0.3;
                                fruitScript.collider.density = fruitScript.getDensityByLevel(fruitData.level);
                        }
                }

                // 延迟一帧后再次确保物理组件正确初始化
                this.scheduleOnce(() => {
                        if (rigid && rigid.isValid) {
                                // rigid.awake = true;
                                rigid.wakeUp();

                                // 强制更新物理状态
                                rigid.linearVelocity = v2(fruitData.linearVelocityX, fruitData.linearVelocityY);
                                rigid.angularVelocity = fruitData.angularVelocity;
                                // 确保刚体被物理系统正确识别
                                rigid.enabled = true;
                        }
                        if (collider && collider.isValid) {
                                collider.enabled = true;
                                // 确保碰撞体被物理系统正确识别
                                collider.apply();
                                // 强制更新碰撞体属性
                                collider.friction = 0.1;
                                collider.restitution = 0.3;
                                collider.density = this.getDensityByLevel(fruitData.level);
                        }

                        // 调试信息
                        // console.log(`恢复水果 ${fruitData.level} 级，位置: (${fruitData.x}, ${fruitData.y})，碰撞体启用: ${collider?.enabled}，刚体类型: ${rigid?.type}`);
                }, 0);

                // 额外延迟一帧，确保物理系统完全识别
                this.scheduleOnce(() => {
                        if (rigid && rigid.isValid && collider && collider.isValid) {
                                // 强制唤醒刚体
                                // rigid.awake = true;
                                rigid.wakeUp();

                                // 确保碰撞体被物理系统识别
                                collider.enabled = true;
                                collider.apply();
                                // console.log(`最终确认：水果 ${fruitData.level} 级物理组件已正确初始化`);
                        }
                }, 0.016); // 一帧的时间

                // 再延迟几帧，确保物理系统完全稳定
                this.scheduleOnce(() => {
                        if (rigid && rigid.isValid && collider && collider.isValid) {
                                // 最终确认物理组件状态
                                // rigid.awake = true;
                                rigid.wakeUp();
                                collider.enabled = true;
                                collider.apply();

                                // 检查物理系统是否正确识别
                                // const physicsManager = director.getPhysicsManager();
                                // if (physicsManager && physicsManager.enabled) {
                                //         // console.log(`物理系统确认：水果 ${fruitData.level} 级已正确注册到物理系统`);
                                // }
                        }
                }, 0.05); // 延迟更多时间确保物理系统稳定
        }
        //    // 获取密度（从水果脚本中复制过来）
        private getDensityByLevel(level: number): number {
                switch (level) {
                        case 1: return 1;
                        case 2: return 1.01;
                        case 3: return 1.02;
                        case 4: return 1.03;
                        case 5: return 1.04;
                        default: return 1.05; // 6级及以上
                }
        }
        //    // 保存当前游戏状态
        private saveCurrentGameState() {
                HeChengDaXiGua_GameStorage.saveFruitsData(this.fruitLayer, HeChengDaXiGua_GameData.Score);

                // 每10秒显示一次保存提示，避免过于频繁
                const currentTime = Date.now();
                if (!this.lastSaveTipTime || currentTime - this.lastSaveTipTime > 10000) {
                        // HeChengDaXiGua_GamePanel.Instance.showSaveTip();
                        this.lastSaveTipTime = currentTime;
                }
        }
        //    // 自动保存
        private autoSave() {
                if (!this.isGameOver) {
                        this.saveCurrentGameState();
                        // console.log("每2秒自动保存游戏状态");
                }
        }
        // //    // 应用隐藏时保存
        // private onAppHide() {
        //         if (!this.isGameOver) {
        //                 this.saveCurrentGameState();
        //                 console.log("应用隐藏，保存游戏状态");
        //         }
        // }
        //    // 拖拽开始
        onTouchStart(event: EventTouch) {
                if (this.isGameOver || !this.currentFruit) return;
                this.isDragging = true;

                // const location = event.getLocation();
                const location = event.getUILocation();
                // const localPos = this.fruitLayer.convertToNodeSpaceAR(location);
                const localPos = this.fruitLayer.getComponent(UITransform).convertToNodeSpaceAR(v3(location.x, location.y));

                // 可加边界限制
                const minX = -this.fruitLayer.getComponent(UITransform).width / 2 + this.currentFruit.getComponent(UITransform).width / 2;
                const maxX = this.fruitLayer.getComponent(UITransform).width / 2 - this.currentFruit.getComponent(UITransform).width / 2;
                let x = Math.max(minX, Math.min(maxX, localPos.x));


                //用this.next的世界坐标y
                // let nextY = this.next.getPosition().y;
                // this.currentFruit.setPosition(x, nextY - 50);

                // this.移动父物体.setPosition(x, nextY);
                this.移动父物体.setPosition(x, this.移动父物体.position.y);

                {
                        // const worldPos = this.当前水果.convertToWorldSpaceAR(v2(0, 0));
                        // const posCenter = v3(this.currentFruit.parent.convertToNodeSpaceAR(worldPos));
                        const worldPos = this.当前水果.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0));
                        const posCenter = v3(this.currentFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos));
                        this.currentFruit.setPosition(posCenter);
                }

                // let previewFruit = this.nextFruitPreview.children[0];
                let previewFruit = this.previewFruit;
                // const worldPos = this.预览水果.convertToWorldSpaceAR(v2(0, 0));
                const worldPos = this.预览水果.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0));
                const posCenter = v3(previewFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos));
                previewFruit.setPosition(posCenter);

                // this.currentFruit.position = v3(0, 0);
        }
        //    // 拖拽中
        onTouchMove(event: EventTouch) {
                if (!this.isDragging || !this.currentFruit) return;
                // const location = event.getLocation();
                const location = event.getUILocation();
                // const localPos = this.fruitLayer.convertToNodeSpaceAR(location);
                const localPos = this.fruitLayer.getComponent(UITransform).convertToNodeSpaceAR(v3(location.x, location.y));

                // 可加边界限制
                const minX = -this.fruitLayer.getComponent(UITransform).width / 2 + this.currentFruit.getComponent(UITransform).width / 2;
                const maxX = this.fruitLayer.getComponent(UITransform).width / 2 - this.currentFruit.getComponent(UITransform).width / 2;
                let x = Math.max(minX, Math.min(maxX, localPos.x));

                //用this.next的世界坐标y
                // let nextY = this.next.getPosition().y;
                // this.currentFruit.setPosition(x, nextY - 50);

                this.移动父物体.setPosition(x, this.移动父物体.position.y);

                {
                        // const worldPos = this.当前水果.convertToWorldSpaceAR(v2(0, 0));
                        // const posCenter = v3(this.currentFruit.parent.convertToNodeSpaceAR(worldPos));
                        const worldPos = this.当前水果.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0));
                        const posCenter = v3(this.currentFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos));
                        this.currentFruit.setPosition(posCenter);
                }

                // let previewFruit = this.nextFruitPreview.children[0];
                // let previewFruit = this.previewFruit;
                // const worldPos = this.预览水果.convertToWorldSpaceAR(v2(0, 0));
                const worldPos = this.预览水果.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0));
                const posCenter = v3(this.previewFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos));
                this.previewFruit.setPosition(posCenter);

                // this.currentFruit.setPosition(0, 0);
        }
        //    // 拖拽结束，投放
        async onTouchEnd(event: EventTouch) {
                if (!this.isDragging || !this.currentFruit) return;

                let root = `audio/落水`;
                bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, root, AudioClip).then(res => {
                        SSS_AudioManager.Instance.playSFX(res, false);
                });

                // 启用碰撞体，允许物理和合并
                const collider = this.currentFruit.getComponent(CircleCollider2D);
                if (collider) {
                        collider.enabled = true;
                }
                // 切换为 Dynamic，下落
                const rigid = this.currentFruit.getComponent(RigidBody2D);
                if (rigid) {
                        // rigid.type = RigidBodyType.Dynamic;
                        rigid.type = ERigidBody2DType.Dynamic;
                }


                this.isDragging = false;
                this.currentFruit = null;

                // 投放后销毁竖线
                // this.destroyGuideLine();

                // 配置时间参数 (单位: 秒)
                const a = 0.3; // 水果下落多久后预览消失
                const b = 0.3; // 预览消失后多久生成新水果
                const c = 0.3; // 新水果生成后多久显示新预览


                await new Promise(res => this.scheduleOnce(res, a));
                await this.hideNextFruitPreview(); //隐藏水果预览

                // await new Promise(res => this.scheduleOnce(res, b));
                await this.generateNewCurrentFruit(); //生成新的当前水果

                // await new Promise(res => this.scheduleOnce(res, c));
                await this.updateNextFruitPreview(); //更新下一个水果预览
        }
        //    // 隐藏水果预览
        async hideNextFruitPreview() {
                // await new Promise<void>((resolve) => {
                //         director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                // });

                const rigid = this.previewFruit.getComponent(RigidBody2D);
                if (rigid) {
                        rigid.enabled = false;
                }
                const collider = this.previewFruit.getComponent(CircleCollider2D);
                if (collider) {
                        collider.enabled = false;
                }
                this.previewFruit.active = false;
        }
        //    // 生成新的当前水果
        async generateNewCurrentFruit() {
                // await new Promise<void>((resolve) => {
                //         director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                // });

                if (this.isGameOver) return;

                if (!this.fruitPrefabs || this.fruitPrefabs.length === 0) {
                        error("fruitPrefabs 为空，请拖入水果预制体");
                        return;
                }

                // 使用之前准备好的下一个水果等级
                let level = this.nextFruitLevel;
                // level = 11; //TODO

                // 生成新的下一个水果等级，用于下次预览
                this.generateNextFruitLevel();

                const prefab = this.fruitPrefabs[level - 1];
                if (!prefab) {
                        error(`没有找到等级 ${level} 的水果预制体`);
                        return;
                }

                const fruit = instantiate(prefab);
                fruit.parent = this.fruitLayer;
                // let nextY = this.next.getPosition().y;

                this.currentFruit = fruit;

                // const worldPos = this.当前水果.convertToWorldSpaceAR(v2(0, 0));
                // const posCenter = v3(this.currentFruit.parent.convertToNodeSpaceAR(worldPos));
                const worldPos = this.当前水果.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0));
                // const posCenter = v3(this.currentFruit.parent.convertToNodeSpaceAR(worldPos));
                // const posCenter = this.currentFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos.clone());
                const posCenter = this.currentFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
                this.currentFruit.setPosition(posCenter);

                const rigid = fruit.getComponent(RigidBody2D);
                if (rigid) {
                        // rigid.enabledContactListener = true; // 启用碰撞监听
                        rigid.bullet = true; // 开启高速防穿透
                        // rigid.type = ERigidBody2DType.Kinematic;
                        rigid.gravityScale = 1;
                        rigid.linearDamping = 0.8;
                        rigid.angularDamping = 0.8;
                        // rigid.fixedRotation = true;
                        rigid.wakeUp();
                        rigid.linearVelocity = v2(0, 0);
                }

                // 禁用碰撞体，防止悬浮阶段合并
                const collider = fruit.getComponent(CircleCollider2D);
                if (collider) {
                        collider.enabled = false;
                }

                const fruitScript = fruit.getComponent(HeChengDaXiGua_Fruit);
                if (fruitScript) {
                        fruitScript.setGameManager(this);
                        fruitScript.level = level;
                        fruitScript.isMerged = false;
                        fruitScript.isLanded = false;
                }

                // 添加淡入动画
                // fruit.opacity = 0;
                // fruit.scale = 0.5;
                fruit.getComponent(UIOpacity).opacity = 255;
                fruit.scale = v3(1, 1, 1);
                // tween(fruit)
                //     .to(0.01, { opacity: 255, scale: 1 })
                //     .start();

                // 生成竖线节点
                this.createGuideLine();
        }
        //    // 生成下一个水果等级
        private generateNextFruitLevel() {
                if (!this.fruitPrefabs || this.fruitPrefabs.length === 0) {
                        this.nextFruitLevel = 1;
                        return;
                }

                // 使用概率逻辑
                const baseProbabilities = [0.5, 0.3, 0.15, 0.05, 0];
                const maxLevel = this.fruitPrefabs.length;
                const probs = baseProbabilities.slice(0, maxLevel);
                // 归一化概率
                const total = probs.reduce((a, b) => a + b, 0);
                for (let i = 0; i < probs.length; i++) {
                        probs[i] /= total;
                }

                // 按概率随机选等级
                const rand = Math.random();
                let cumulative = 0;
                let level = 1;
                for (let i = 0; i < probs.length; i++) {
                        cumulative += probs[i];
                        if (rand <= cumulative) {
                                level = i + 1;
                                break;
                        }
                }

                this.nextFruitLevel = level;
        }
        //    // 初始化下一个水果等级
        private initNextFruitLevel() {
                this.generateNextFruitLevel();
                // console.log(`初始水果等级已设置: ${this.nextFruitLevel}`);
        }
        //    // 更新下一个水果预览
        async updateNextFruitPreview() {
                // 确保水果等级有效
                if (!this.nextFruitLevel || this.nextFruitLevel <= 0) {
                        console.error(`无效的水果等级: ${this.nextFruitLevel}，重新生成`);
                        this.generateNextFruitLevel();
                        return;
                }

                // console.log(`准备更新预览，水果等级: ${this.nextFruitLevel}`);
                // 清除旧的预览
                // this.nextFruitPreview.removeAllChildren();

                // 验证水果等级和预制体
                if (this.nextFruitLevel <= 0 || this.nextFruitLevel > this.fruitPrefabs.length) {
                        console.error(`无效的水果等级: ${this.nextFruitLevel}`);
                        return;
                }

                // 创建新的预览水果
                const prefab = this.fruitPrefabs[this.nextFruitLevel - 1];
                // console.log(`创建新的预览水果-prefab----------------`, prefab)
                if (prefab) {
                        this.previewFruit = instantiate(prefab);
                        this.previewFruit.parent = this.Root_main;

                        // const worldPos = this.预览水果.convertToWorldSpaceAR(v2(0, 0));
                        const worldPos = this.预览水果.getWorldPosition();
                        // const posCenter = v3(this.previewFruit.parent.convertToNodeSpaceAR(worldPos));
                        const posCenter = v3(this.previewFruit.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPos));
                        this.previewFruit.setPosition(posCenter);

                        this.previewFruit.scale = v3(0.5, 0.5, 1); // 缩小初始大小
                        this.previewFruit.getComponent(UIOpacity).opacity = 0; // 初始透明

                        // 确保预览水果可见
                        this.previewFruit.active = true;

                        // 禁用物理组件，避免影响游戏
                        const rigid = this.previewFruit.getComponent(RigidBody2D);
                        if (rigid) {
                                rigid.enabled = false;
                        }
                        const collider = this.previewFruit.getComponent(CircleCollider2D);
                        if (collider) {
                                collider.enabled = false;
                        }

                        let d1 = 0.01;
                        // 添加淡入动画
                        // tween(previewFruit)
                        //     .to(d1, { opacity: 255, scale: 0.7 })
                        //     .start();
                        this.previewFruit.getComponent(UIOpacity).opacity = 255;
                        this.previewFruit.scale = v3(0.7, 0.7, 1);

                        // await new Promise(res => this.scheduleOnce(res, d1 + 0.01));


                        // console.log(`已更新预览水果，等级: ${this.nextFruitLevel}`);
                } else {
                        // console.error(`无法找到等级为 ${this.nextFruitLevel} 的水果预制体`);
                }
        }
        //    // 旧的spawnNextFruit方法，保留以避免引用错误
        //    // 新逻辑已迁移至generateNewCurrentFruit和generateNextFruitLevel方法
        spawnNextFruit() {
                this.generateNewCurrentFruit();
        }
        //    // 创建竖线节点
        private createGuideLine() {
                if (this.guideLineNode && this.guideLineNode.isValid) {
                        this.guideLineNode.destroy();
                }
                if (!this.currentFruit) return;
                this.guideLineNode = new Node("GuideLine");
                this.guideLineGraphics = this.guideLineNode.addComponent(Graphics);
                // this.guideLineNode.parent = this.fruitLayer;
                this.guideLineNode.parent = this.lineLayer;
                this.guideLineNode.zIndex = 999;
        }

        // //    // 销毁竖线节点
        // private destroyGuideLine() {
        //         if (this.guideLineNode && this.guideLineNode.isValid) {
        //                 this.guideLineNode.destroy();
        //                 this.guideLineNode = null;
        //                 this.guideLineGraphics = null;
        //         }
        // }

        async mergeFruits(fruitA: HeChengDaXiGua_Fruit, fruitB: HeChengDaXiGua_Fruit) {
                // director.once(Director.EVENT_AFTER_PHYSICS, () => {
                // console.log(`合并水果`)
                // console.log(`fruitA`, fruitA);
                // console.log(`fruitB`, fruitB);

                // if (!fruitA || !fruitB || !fruitA.isValid || !fruitB.isValid) return;
                const nodeA = fruitA.node;
                const nodeB = fruitB.node;

                const currentLevel = fruitA.level;
                if (currentLevel >= this.fruitPrefabs.length) {
                        return;
                }

                // 替换原来的位置计算代码
                const worldPosA = nodeA.getWorldPosition();
                const worldPosB = nodeB.getWorldPosition();
                // 计算世界坐标系中的中点
                const worldCenter = new Vec3(
                        (worldPosA.x + worldPosB.x) * 0.5,
                        (worldPosA.y + worldPosB.y) * 0.5,
                        0
                );
                // 将世界坐标转换回fruitLayer的本地坐标系
                let newPos = this.fruitLayer.getComponent(UITransform).convertToNodeSpaceAR(worldCenter);
                newPos = v3(newPos.x, newPos.y + 10, newPos.z);
                // newPos.y += 10;

                fruitA.isMerged = true;
                fruitB.isMerged = true;

                const colliderA = nodeA.getComponent(CircleCollider2D);
                const colliderB = nodeB.getComponent(CircleCollider2D);
                if (colliderA) colliderA.enabled = false;
                if (colliderB) colliderB.enabled = false;

                tween(nodeA)
                        .to(0.15, { scale: v3(0, 0, 1) })
                        .call(() => {
                                if (nodeA && nodeA.isValid) nodeA.destroy();
                        })
                        .start();

                tween(nodeB)
                        .to(0.15, { scale: v3(0, 0, 1) })
                        .call(() => {
                                if (nodeB && nodeB.isValid) nodeB.destroy();
                        })
                        .start();

                // await new Promise(res => this.scheduleOnce(res, 0.001));
                // await new Promise<void>((resolve) => {
                //         director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                // });

                const newLevel = currentLevel + 1;
                const prefab = this.fruitPrefabs[newLevel - 1];
                if (!prefab) {
                        error('没有对应等级的预制体');
                        return;
                }

                const newFruitNode = instantiate(prefab);

                // console.log(`newFruitNode---------222-------`, newFruitNode);
                // console.log(`newFruitNode----------------`, newFruitNode)

                // console.log(`newFruitNode----------------`, newFruitNode)
                // console.log(`newPos----------------`, newPos)

                // newFruitNode.setPosition(newPos);
                // newFruitNode.worldPosition = newPos;
                // director.once(Director.EVENT_AFTER_PHYSICS, () => {
                // newFruitNode.position = v3(-200, 300, 0);
                newFruitNode.parent = this.fruitLayer;

                // this.scheduleOnce(() => {
                // newFruitNode.position = newPos// v3(200, -300, 0);
                newFruitNode.setPosition(newPos);

                // }, 0.5);
                // }, this)

                // newFruitNode.scaleX = 0.5;
                // newFruitNode.scaleY = 0.5;
                newFruitNode.scale = v3(0.5, 0.5, newFruitNode.scale.z)

                tween(newFruitNode)
                        // .to(0.2, { scaleX: 1.2, scaleY: 1.2 }, easeBackOut())
                        // .to(0.1, { scaleX: 1, scaleY: 1 }, easeBackIn())
                        .to(0.2, { scale: new Vec3(1.2, 1.2, 1) }, { easing: easing.backOut })  // 缓动改成 easing.backOut
                        .to(0.1, { scale: new Vec3(1, 1, 1) }, { easing: easing.backIn })  // 缓动改成 easing.backOut
                        .start();

                let r = randomRangeInt(1, 3);
                let root = `audio/水音效${r}`;
                bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, root, AudioClip).then(res => {
                        SSS_AudioManager.Instance.playSFX(res);
                });

                const rigid = newFruitNode.getComponent(RigidBody2D);
                if (rigid) {
                        rigid.type = ERigidBody2DType.Dynamic; // RigidBodyType.Dynamic;
                        rigid.gravityScale = 1;
                        rigid.linearDamping = 0.8;
                        rigid.angularDamping = 0.8;
                        // rigid.fixedRotation = true;
                        // rigid.awake = true;
                        // rigid.wakeUp();
                        rigid.linearVelocity = v2(0, 0);
                }

                const newFruitScript = newFruitNode.getComponent(HeChengDaXiGua_Fruit);
                if (newFruitScript) {
                        newFruitScript.level = newLevel;
                        newFruitScript.setGameManager(this);
                        newFruitScript.isMerged = false;
                        newFruitScript.isLanded = false;
                }

                this.addScore(newLevel);
                // }

                // }, this)
        }

        addScore(level: number) {
                const gained = Math.pow(2, level + 1);
                HeChengDaXiGua_GameData.Score += gained;

                //如果比最高分高，更新最高分
                if (HeChengDaXiGua_GameData.Score > HeChengDaXiGua_GameStorage.data.high_score) {
                        HeChengDaXiGua_GameStorage.data.high_score = HeChengDaXiGua_GameData.Score;
                        HeChengDaXiGua_GameStorage.saveData();
                }

                HeChengDaXiGua_GamePanel.Instance.Refresh_score();
        }

        async update(dt: number) {
                // director.once(Director.EVENT_AFTER_PHYSICS, () => {

                if (this.isGameOver) return;

                // 虚线流动动画
                const dashLen = 6;
                const gapLen = 18;
                const totalLen = dashLen + gapLen;
                const speed = 30// 30; // 每秒60像素
                this.dashOffset += dt * speed;
                if (this.dashOffset > totalLen) {
                        this.dashOffset -= totalLen;
                }

                // 更新竖线
                this.updateGuideLine();

                let overHeightAndSlow = false;


                // await new Promise<void>((resolve) => {
                //         director.once(Director.EVENT_AFTER_PHYSICS, resolve);
                // });

                this.fruitLayer.children.forEach(fruitNode => {
                        // console.log()
                        if (!fruitNode || !fruitNode.isValid) return;
                        if (fruitNode === this.currentFruit) return;

                        const rigid = fruitNode.getComponent(RigidBody2D);
                        if (!rigid) return;

                        const speed = rigid.linearVelocity.length(); //rigid.linearVelocity.mag();
                        // const fruitHeight = fruitNode.getContentSize().height * fruitNode.scaleY;
                        const fruitHeight = fruitNode.getComponent(UITransform).height * fruitNode.scale.y; // 或者 uiTrans.contentSize.y * fruitNode.scale.y

                        // 计算水果顶部世界坐标
                        const fruitTopWorld = fruitNode.parent.getComponent(UITransform).convertToWorldSpaceAR(
                                v3(fruitNode.position.x, fruitNode.position.y + fruitHeight / 2)
                        );
                        // 计算死亡线世界坐标
                        const deadLineWorld = this.DeadLine.parent.getComponent(UITransform).convertToWorldSpaceAR(
                                this.DeadLine.getPosition()
                        );

                        if (fruitTopWorld.y > deadLineWorld.y && speed < this.speedThreshold) {
                                overHeightAndSlow = true;
                        }
                });


                if (overHeightAndSlow) {
                        this.dangerFrameCount++;
                        if (this.dangerFrameCount >= this.dangerFrameThreshold) {
                                this.gameOver();
                        }
                } else {
                        this.dangerFrameCount = 0;
                }

                // 限制所有 Dynamic 刚体最大下落速度，防止穿透
                const maxV = 1500;
                this.fruitLayer.children.forEach(fruitNode => {
                        const rigid = fruitNode.getComponent(RigidBody2D);
                        if (rigid) {
                                // 定期唤醒所有刚体，防止静止穿透
                                // rigid.awake = true;
                                // rigid.wakeUp();

                        }
                        // if (rigid && rigid.type === RigidBodyType.Dynamic) {
                        if (rigid && rigid.type === ERigidBody2DType.Dynamic) {
                                if (rigid.linearVelocity.y < -maxV) {
                                        rigid.linearVelocity = v2(rigid.linearVelocity.x, -maxV);
                                }
                        }
                });

                // }, this)
        }

        updateGuideLine() {
                if (!this.guideLineNode || !this.guideLineGraphics) return;

                const startX = this.移动父物体.position.x + 13;
                const startY = this.移动父物体.position.y;

                const startWorld = this.fruitLayer.getComponent(UITransform).convertToWorldSpaceAR(v3(startX, startY));

                // 设置射线终点（向下2000单位）
                let endWorld = v2(startWorld.x, startWorld.y - 2000);
                let hitPoint = null; // endWorld.clone();
                const results = PhysicsSystem2D.instance.raycast(startWorld, endWorld, ERaycast2DType.All);
                // if (results.length > 0) {
                //         for (const result of results) {
                //                 if (result.collider.node === this.地) {
                //                         hitPoint = result.point;
                //                         break;
                //                 }
                //         }
                // }
                if (results.length > 0) {
                        let minDist = Number.MAX_VALUE;
                        for (let i = 0; i < results.length; i++) {
                                const node = results[i].collider.node;
                                // if (node !== this.DeadLine) {
                                if (node === this.地) {
                                        // const dist = startWorld.sub(results[i].point).mag();
                                        const dist = Vec2.subtract(new Vec2(), v2(startWorld.x, startWorld.y), results[i].point).length();
                                        if (dist < minDist) {
                                                minDist = dist;
                                                hitPoint = results[i].point;
                                        }
                                }
                        }
                }
                if (!hitPoint) {
                        hitPoint = endWorld;
                }

                // 将终点转换回节点本地坐标
                const endLocal = this.fruitLayer.getComponent(UITransform).convertToNodeSpaceAR(v3(hitPoint.x, hitPoint.y, hitPoint.z));

                this.guideLineNode.setPosition(startX, 0);
                this.guideLineGraphics.clear();
                this.guideLineGraphics.lineWidth = 10;
                this.guideLineGraphics.strokeColor = new Color(255, 80, 0, 255);

                // 绘制虚线
                const dashLen = 6;
                const gapLen = 18;
                let y = startY - this.dashOffset;
                while (y > endLocal.y) {
                        let nextY = Math.max(y - dashLen, endLocal.y);
                        this.guideLineGraphics.moveTo(0, y);
                        this.guideLineGraphics.lineTo(0, nextY);
                        y = nextY - gapLen;
                }

                // 完成绘制
                this.guideLineGraphics.stroke();
        }

        gameOver() {
                if (this.isGameOver) return;

                this.isGameOver = true;
                console.log("游戏结束！");

                if (this.touchLayer) {
                        this.touchLayer.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
                        this.touchLayer.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
                        this.touchLayer.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
                }

                this.Lose();
        }
        Lose() {
                UI.Instance.CreatePanel_sub(`HeChengDaXiGua_Prefab`, `UI/HeChengDaXiGua_LosePanel`, HeChengDaXiGua_LosePanel);

                HeChengDaXiGua_GameData.clearFruitsData();
        }
        onDestroy() {
                // 清理事件监听
                // game.off(game.EVENT_HIDE, this.onAppHide, this);
        }
        Replay() {
                HeChengDaXiGua_GameData.ClearData();

                // 清除保存的游戏状态
                HeChengDaXiGua_GameStorage.clearFruitsData();

                // 确保物理系统被正确重置
                // const physicsManager = director.getPhysicsManager();
                // if (physicsManager) {
                //         physicsManager.enabled = false;
                //         physicsManager.enabled = true;
                // }
                PhysicsSystem2D.instance.enable = false;
                PhysicsSystem2D.instance.enable = true;

                let currentSceneName = director.getScene().name;
                director.loadScene(currentSceneName);
        }
}